package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.util.volleyUtil.ResponseListener;
import com.century.sjt.util.CompressUtil;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.util.UploadApi;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:周玲波
 * @Description: 个人资料设置
 * @date : 2016/8/18 10:32
 */
public class MydataActivity extends BaseActivity{
    private SjtTitleBar titleBar;
    private RadioGroup raGroup;
    private RadioButton tbMale;
    private RadioButton tbFemale;

    private LinearLayout layoutAddress;
    private LinearLayout layoutEWnumber;
    private EditText tvNickName;
    private TextView tvBirthday;
    private TextView t_aphome;
    private ImageView ciHeadimage;
    private Calendar calendar;
    private String birthday = "";
    private String gender = "";
    private String nickName = "";
    private String whatsUp;
    private String image = "";
    private String tname="";

    private String aphome;

    private ImageView ivGallery, ivCamera;                   //设置头像
    private String localCameraPath = "";

    private Bitmap centerBmp;

    private ProgressDialog dialog;

    private Uri imageUri;

    private TextView tvWhatsUp;
    private LinearLayout layout_GXQM;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_me_data_activity);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//软键盘设置

        initViews();
        initEvents();
        showLoginContent();//获取用户信息
    }
    private void initViews() {
        titleBar = (SjtTitleBar) findViewById(R.id.me_data_title);
        raGroup = (RadioGroup) findViewById(R.id.rg_activity_login_ragroup);
        tbMale = (RadioButton) findViewById(R.id.rb_ragroup_m);
        tbFemale = (RadioButton) findViewById(R.id.rg_ragroup_f);
        tvNickName = (EditText) findViewById(R.id.t_name);
        tvBirthday = (TextView) findViewById(R.id.tv_birthday);
        ciHeadimage = (ImageView) findViewById(R.id.me_touxiang_image);
        t_aphome=(TextView) findViewById(R.id.t_aphome);
        layoutAddress =(LinearLayout) findViewById(R.id.layout_addressmanage);
        layoutEWnumber = (LinearLayout) findViewById(R.id.layout_ewmnumber);
        tvWhatsUp = (TextView) findViewById(R.id.tv_whatsup);
        layout_GXQM = (LinearLayout) findViewById(R.id.layout_gxqm);
    }
    private void initEvents() {
        //       标题栏
        titleBar.setTitle(getString(R.string.tab_me_data));
        titleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        titleBar.setRightIconResourc(getResources().getString(R.string.btn_save));
        titleBar.setRightIconSize();
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveInfo();
            }
        });
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //        获取时间
        calendar = Calendar.getInstance();
//        性别单选框
        raGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                if (checkedId == R.id.rb_ragroup_m) {
                    gender = "M";
                } else {
                    gender = "F";
                }
            }
        });
        layoutAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MydataActivity.this, AddressManageActivity.class);
                startActivity(intent);
            }
        });
        layoutEWnumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent1 = new Intent(MydataActivity.this, MyQRRecordActivity.class);
               startActivity(intent1);
            }
        });
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        tname = mainSharedPreferences.getString("name", "");
        String isRealName = mainSharedPreferences.getString("isRealName", "");
        layout_GXQM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MydataActivity.this, EditAutographActivity.class);
                startActivity(intent1);
            }
        });

    }

    public void headImageEvent(View view) {
        View layout = LayoutInflater.from(MydataActivity.this).inflate(R.layout.choose_photo_type_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(MydataActivity.this);
        builder.setCancelable(false);
        builder.setTitle(getResources().getString(R.string.tab_set_head));
        builder.setView(layout);
        ivGallery = (ImageView) layout.findViewById(R.id.iv_choose_photo_type_gallery);
        ivCamera = (ImageView) layout.findViewById(R.id.iv_choose_photo_take_camera);
        final AlertDialog dialog = builder.show();
        ivGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, Constant.REQUESTCODE_TAKE_LOCAL);
            }
        });
        ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File dir = new File(Constant.CAMERA_PICTURE_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, String.valueOf(System.currentTimeMillis())
                        + ".jpg");
                localCameraPath = file.getPath();
                imageUri = Uri.fromFile(file);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(openCameraIntent,
                        Constant.REQUESTCODE_TAKE_CAMERA);
            }
        });

        Button btn_Cancel = (Button) layout.findViewById(R.id.btn_choose_photo_type_cancel);
        btn_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUESTCODE_TAKE_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (!localCameraPath.equals("")) {
                        Bitmap bitmap = CompressUtil.compressImg(localCameraPath);
                        centerBmp = CompressUtil.centerSquareScaleBitmap(bitmap, 256);
                        //剪切头像
                        startPhotoZoom(imageUri);
                    }
                }
                break;
            case Constant.REQUESTCODE_TAKE_LOCAL:
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        Cursor cursor = getContentResolver().query(
                                selectedImage, null, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex("_data");
                        String localSelectPath = cursor.getString(columnIndex);
                        cursor.close();
                        if (localSelectPath == null
                                || localSelectPath.equals("null")) {
                            TipUtil.showToast(getResources().getString(R.string.error_cancel_sending), MydataActivity.this);
                            return;
                        } else {
                            if (resultCode == RESULT_OK) {
                                if (!localSelectPath.equals("")) {
                                    Bitmap bitmap = CompressUtil.compressImg(localSelectPath);
                                    centerBmp = CompressUtil.centerSquareScaleBitmap(bitmap, 256);
                                    //剪切头像
                                    startPhotoZoom(selectedImage);
                                }
                            }
                        }
                    }
                }
                break;
            case Constant.REQUESTCODE_CUTTING:
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
    }

    public void saveInfo() {
        nickName = tvNickName.getText().toString();
        birthday = tvBirthday.getText().toString();
        if (nickName == null || nickName == "" || nickName == "未填写") {
            TipUtil.showToast(getResources().getString(R.string.enter_nickname), MydataActivity.this, 1);
        } else if (gender == null || gender == "" || gender == "未填写") {
            TipUtil.showToast(getResources().getString(R.string.enter_gender), MydataActivity.this, 1);
        } else if (birthday == null || birthday == "" || birthday == "未填写") {
            TipUtil.showToast(getResources().getString(R.string.enter_birthday), MydataActivity.this, 1);
        } else {
            saveUserInfo();
        }
    }
    private void upLoadImage(final Bitmap photo) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MydataActivity.this);
        UploadApi.uploadImg(centerBmp, new ResponseListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.closeProgressDialog();
                TipUtil.log("上传图片接口失败返回", error.getLocalizedMessage(), 1);
                TipUtil.showToast(getResources().getString(R.string.error_network), MydataActivity.this, 1);
            }
            @Override
            public void onResponse(Object response) {
                TipUtil.closeProgressDialog();
                TipUtil.log("上传图片接口成功返回", response.toString(), 1);
                try {
                    JSONTokener jsonParser = new JSONTokener((String) response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        image = data.getString("sysId");             //服务器发来的图片id
                        ciHeadimage.setImageBitmap(centerBmp);
                    } else {
                        String message = res.getString("message");
                        Toast.makeText(MydataActivity.this, getResources().getString(R.string.error_upload_failed) + message, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, mQueue);
    }

    private void saveUserInfo() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MydataActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.UpdateDetailHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("保存用户信息接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        nickName = tvNickName.getText().toString();
                        birthday = tvBirthday.getText().toString();
                        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = mainSharedPreferences.edit();
                        editor.putString("birthday", birthday.trim());
                        editor.putString("nickName", nickName.trim());
                        editor.putString("gender", gender.trim());
                        editor.putString("image", image.trim());
                        editor.commit();
                        SjtHelper.getInstance().GetMyEaseData();
                        finish();
                    } else {//失败
                        TipUtil.showToast(message, MydataActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MydataActivity.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MydataActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                nickName = tvNickName.getText().toString();
                birthday = tvBirthday.getText().toString();
                map.put("image", image);
                map.put("gender", gender);
                map.put("birthday", birthday);
                map.put("nickName", nickName);
                map.put("loginId", userId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }
    @Override
    protected void onResume() {
        super.onResume();
        initEvents();
        showLoginContent();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    //    用户信息
    private void showLoginContent() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        birthday = sharedPreferences.getString("birthday", "");
        String idCard = sharedPreferences.getString("idCard", "");
        nickName = sharedPreferences.getString("nickName", "");
        whatsUp = sharedPreferences .getString("whatsUp","");
        String name = sharedPreferences.getString("name", "");
        String userId = sharedPreferences.getString("userId", "");
//        inviteCode = sharedPreferences.getString("inviteCode", "");
        gender = sharedPreferences.getString("gender", "");
        image = sharedPreferences.getString("image", "");
        String isRealName = sharedPreferences.getString("isRealName", "");
        String nativeAddr = sharedPreferences.getString("nativeAddr", "");
        String mobile = sharedPreferences.getString("mobile", "");

        if (gender.equals("F")) {
            tbFemale.setChecked(true);
            gender = "F";
        } else {
            tbMale.setChecked(true);
            gender = "M";
        }
        //  获取头像实例
        if (!"".equals(image)) {
            Glide.with(MydataActivity.this).load(Constant.ImageHost_Big+image).into(ciHeadimage);
//            FileUtil.setupBigImage(image, mQueue, ciHeadimage);
        }


        //昵称
        if (nickName.equals("")) {
            tvNickName.setText(getResources().getString(R.string.app_user));
        } else {
            tvNickName.setText(nickName);
        }
        //手机号码
        if (mobile.equals("")||mobile==null){
            t_aphome.setText(getResources().getString(R.string.error_is_null));
        }else {
            t_aphome.setText(mobile.substring(0,3)+" **** "+mobile.substring(mobile.length()-4,mobile.length()));
        }

        //生日
        if (birthday.equals("")) {
            tvBirthday.setText("2016-01-01");
        } else {
            tvBirthday.setText(birthday);
        }
        //邀请码

//        if (inviteCode.equals("")) {
//            tvInviteCode.setText("");
//        } else {
//            tvInviteCode.setText(inviteCode);
//        }

        if ("".equals(whatsUp)||null==whatsUp){

        }else {
            tvWhatsUp.setText(whatsUp);
        }
    }

    //    日期控件
    public void showDateDialog(View view) {
        String birth = tvBirthday.getText().toString().trim();
        DatePickerDialog date_dialog;
        if ("".equals(birth)) {
            date_dialog = new DatePickerDialog(MydataActivity.this, dateListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        } else {
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            try {
                String strYear = birth.substring(0, 4);
                String strMonth = birth.substring(5, 7);
                String strDay = birth.substring(8, 10);
//                TipUtil.showToast(strYear+strMonth+strDay,BasicResumeActivity.this);
                year = Integer.parseInt(strYear);
                month = Integer.parseInt(strMonth) - 1;
                day = Integer.parseInt(strDay);
            } catch (Exception e) {

            }
            date_dialog = new DatePickerDialog(MydataActivity.this, dateListener, year, month, day);
        }
        date_dialog.show();
    }

    private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            if (monthOfYear > 8) {
                if (dayOfMonth > 9) {
                    birthday = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                } else {
                    birthday = year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth;
                }
            } else {
                if (dayOfMonth > 9) {
                    birthday = year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth;
                } else {
                    birthday = year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth;
                }
            }
//            basic_resume_birthday.setText(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth);
            tvBirthday.setText(birthday);
        }
    };

    public void showIdentityInfo(View view) {
        Intent intent = new Intent();
        intent.setClass(MydataActivity.this, IdentityInfoActivity.class);
        startActivity(intent);
    }
    /**
     * 用户头像——包含压缩上传等
     */

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, Constant.REQUESTCODE_CUTTING);
    }
    /**
     * save the picture data
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = CompressUtil.centerSquareScaleBitmap(photo, 256);
            Drawable drawable = new BitmapDrawable(getResources(), photo);
            ciHeadimage.setImageDrawable(drawable);

            upLoadImage(photo);//sjt服务器

        }

        }
        @Override
        protected void initView () {

        }

        @Override
        protected void initEvent () {

        }

        @Override
        protected void initData () {

        }



}
